package cn.xval.ft.app.gen.service.impl;

import cn.xval.fc.base.exception.Asserts;
import cn.xval.fc.base.exception.BusinessException;
import cn.xval.fc.core.security.TokenContext;
import cn.xval.ft.app.gen.database.entity.FutureAccount;
import cn.xval.ft.app.gen.database.repository.FutureAccountRepository;
import cn.xval.ft.app.gen.params.FutureAccountParams;
import cn.xval.ft.app.gen.service.FutureAccountService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class FutureAccountImpl extends TokenContext implements FutureAccountService {
    @Resource
    private FutureAccountRepository repoFutureAccount;
    @Override
    public FutureAccountParams.FutureAccountInfo create(FutureAccountParams.FutureAccountCreateRequest arg) throws BusinessException {
        var entity = new FutureAccount();
        entity.setName(arg.getName());
        entity.setUserId(arg.getUserId());
        entity.setPassword(arg.getPassword());
        entity.setBrokerId(arg.getBrokerId());
        entity.setBroker(arg.getBroker());
        this.repoFutureAccount.save(entity);
        return translate2Info(entity);
    }
    @Override
    public void remove(String id) throws BusinessException {
        this.repoFutureAccount.deleteById(decryptLong(id));
    }
    @Override
    public FutureAccountParams.FutureAccountInfo modify(FutureAccountParams.FutureAccountModifyRequest arg) throws BusinessException {
        var entityId = decryptLong(arg.getId());
        var entityOpt = this.repoFutureAccount.findById(entityId);
        Asserts.Business.withStatusText("记录不存在").assertTrue(entityOpt.isPresent(), "记录不存在: %s", entityId);
        var entity = entityOpt.get();
        entity.setUserId(arg.getUserId());
        entity.setBrokerId(arg.getBrokerId());
        entity.setName(arg.getName());
        entity.setPassword(arg.getPassword());
        entity.setBroker(arg.getBroker());
        this.repoFutureAccount.save(entity);
        return translate2Info(entity);
    }
    @Override
    public List<FutureAccountParams.FutureAccountInfo> list() throws BusinessException {
        var sortInfo = Sort.by(Sort.Order.asc("id"));
        var list = this.repoFutureAccount.findAll(sortInfo);
        var results = new ArrayList<FutureAccountParams.FutureAccountInfo>();
        for (var ent: list) {
            results.add(translate2Info(ent));
        }
        return results;
    }
    public FutureAccountParams.FutureAccountInfo translate2Info(FutureAccount arg) throws BusinessException {
        var info = new FutureAccountParams.FutureAccountInfo();
        info.setId(encrypt(arg.getId()));
        info.setPassword(arg.getPassword());
        info.setName(arg.getName());
        info.setUserId(arg.getUserId());
        info.setBrokerId(arg.getBrokerId());
        info.setBroker(arg.getBroker());
        return info;
    }
}

